import api from './api.js'

// 全局定义组件
Vue.component('products', {
  template: `
    <ul>
      <li v-for="product in products">
        {{product.title}}：￥{{product.price}} <button :disabled="product.inventory <= 0" @click="addToCart(product)">放入购物车</button>
      </li>
    </ul>
  `,

  data() {
    return {
      products: [],
      cartItems: []
    }
  },

  async mounted() {
    const promise = api.getProducts()
    console.log(promise)
    const result = await promise
    this.products = result
  },

  methods: {
    addToCart(product) {
      const result = this.cartItems.find(item => item.id === product.id)
      if (result) {
        result.quantity++
      } else {
        this.cartItems.push({
          ...product,
          quantity: 1
        })
      }
      // 减少库存
      product.inventory--
      this.$emit('add-to-cart', this.cartItems)
    }
  },
})